﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Automation.Protocols.Dao;
using Automation.Protocols.Model;
using Common.Logging;
using SupportLibrary.Message;
using SupportLibrary;

namespace Automation.Dal.Excel.Dao
{
    public class TestDataDao : TestDataBase
    {
        private ExcelProvider _exProvider;
        private string _Path;
        private ILog log = LogManager.GetLogger(typeof(TestDataDao));
        public TestDataDao(string path)
        {
            _Path = path;
            _exProvider = ExcelProvider.Create(@path);
            if (_exProvider == null)
                //MessageShow.FileDoesNotExist(path);
                throw new Exception(path + "doesnot exist!");
        }

         ~TestDataDao()
        {
            _exProvider.SubmitChanges();
        }

        public override List<TestData> getTestdatas()
        {
            List<TestData> list = new List<TestData>();
           // Console.WriteLine("READING SHEET TData.");
            log.Debug(Resources.Information.msg_ReadingSheetTData);
            try
            {
                if (_exProvider != null)
                {
                    var TestDatas = _exProvider.GetSheet<Automation.Dal.Excel.Model.TestData>();
                    int i = 0;
                    if (TestDatas != null)
                    {
                        foreach (Automation.Dal.Excel.Model.TestData item in TestDatas)
                        {
                            if (item.ID != null)
                            {
                                i++;
                                if (item.isValid())
                                    list.Add(new TestData() { 
                                        ID = item.ID,
                                        Comment = item.Comment,
                                        Result = item.Result,
                                        TestCase = item.TestCase,
                                        Values = item.Values
                                    });
                                else
                                {
                                    //MessageShow.InvalidRecord(i + 1);
                                    throw new Exception("Record "+(i+1)+" is invalid!");
                                }
                            }
                        }
                    }
                    //Console.WriteLine(i + " records were read in sheet TData.");
                    log.Debug(Message.ReplaceMessage(Resources.Information.msg_NumofRecord, ByKey.ByNumber(), i.ToString()));
                }
            }
            catch (Exception e)
            {
                log.Error(Resources.ErrorMessage.ReadTDataSheetErr + e.GetType().ToString() + e.Message);
                //MessageShow.ExceptionOccur("Read TData sheet exception.", e);
                throw new Exception(Resources.ErrorMessage.ReadTDataSheetErr + e.GetType().ToString());
            }
            return list;
        }

        public override void RefreshTDatas()
        {
            try
            {
                if (_exProvider != null)
                {
                    var TestDatas = _exProvider.GetSheet<Automation.Dal.Excel.Model.TestData>();

                    if (TestDatas != null)
                    {
                        foreach (Automation.Dal.Excel.Model.TestData item in TestDatas)
                        {
                            if (item.ID != null)
                            {
                                if (item.isValid())
                                {
                                    if (!item.Result.Equals("NOTRUN"))
                                    {
                                        item.Result = "NOTRUN";
                                        try
                                        {
                                            _exProvider.GetSheet<Automation.Dal.Excel.Model.TestData>().UpdateOnSubmit(item);
                                        }
                                        catch (Exception e) { }
                                    }
                                }
                            }
                        }
                        _exProvider.SubmitChanges();
                    }

                }
            }
            catch (Exception e)
            {
                log.Error(Resources.ErrorMessage.ReadTDataSheetErr + e.GetType().ToString() + e.Message);
                //MessageShow.ExceptionOccur("Read TData sheet exception.", e);
                throw new Exception(Resources.ErrorMessage.ReadTDataSheetErr + e.GetType().ToString());
            }
        }

        public override void UpdateDatas(List<TestData> datas)
        {
            try
            {
                if (_exProvider != null)
                {
                    var listNotRun = (from p in _exProvider.GetSheet<TestData>() where p.Result == Resources.Information.NOTRUN select p);
                    foreach (var i in datas)
                    {
                        try
                        {
                            int validNumber = 255;//255 characters
                            int Num = i.Comment.Length;
                            if (Num >= validNumber)
                            {
                                string comment = i.Comment.Remove(validNumber - 1);
                                i.Comment = comment;
                            }

                            foreach (TestData item in listNotRun)
                            {
                                if (item.ID == i.ID && item.Result == Resources.Information.NOTRUN)
                                {
                                    if (item.isValid())
                                    {

                                            item.ID = i.ID;
                                            item.Comment = i.Comment;
                                            item.Result = i.Result;
                                            item.TestCase = i.TestCase;
                                            item.Values = i.Values;                            
                                           _exProvider.GetSheet<TestData>().UpdateOnSubmit(item);
                                           break;
                                                    
                                    }
                                }
                            }
                            
                        }
                        catch (Exception ex)
                        {
                            log.Debug(Resources.ErrorMessage.UpdateTDataErr + ex.GetType().ToString() + ex.Message);
                            throw new Exception(Resources.ErrorMessage.UpdateTDataErr + ex.GetType().ToString());
                        }
                    }
                    _exProvider.SubmitChanges();

                }
            }
            catch (Exception e)
            {
                //MessageShow.ExceptionOccur("Update TStep sheet exception.", e);
                log.Error(Resources.ErrorMessage.UpdateTStepErr + e.GetType().ToString() + e.Message);
                throw new Exception(Resources.ErrorMessage.UpdateTStepErr + e.GetType().ToString());
            }
            
        }

        public override int getTestDataIndex()
        {
            int i = 0;
            try
            {
                if (_exProvider != null)
                {
                    var TestDatas = _exProvider.GetSheet<TestData>();
                    if (TestDatas != null)
                    {
                        foreach (TestData item in TestDatas)
                        {
                            if (item.ID != null)
                                i++;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //MessageShow.ExceptionOccur("Read TData sheet exception.", e);
                log.Error(Resources.ErrorMessage.ReadTDataSheetErr + e.GetType().ToString() + e.Message);
                throw new Exception(Resources.ErrorMessage.ReadTDataSheetErr + e.GetType().ToString());
            }
            return i + 1;
        }

        public override void GenerateTestdatas(List<TestData> tdatas)
        {
            try
            {
                if (_exProvider != null)
                {
                    foreach (var i in tdatas)
                    {
                        TestData item = new TestData()
                        {
                            ID = i.ID,
                            Comment = i.Comment,
                            Result = i.Result,
                            TestCase = i.TestCase,
                            Values = i.Values
                        };
                        _exProvider.GetSheet<TestData>().InsertOnSubmit(item);
                    }
                    //_exProvider.SubmitChanges();
            
                }
            }
            catch (Exception e)
            {
                //MessageShow.ExceptionOccur("Generate TData sheet exception.", e);
                log.Error(Resources.ErrorMessage.GenerateTDataSheetErr + e.GetType().ToString() + e.Message);
                throw new Exception(Resources.ErrorMessage.GenerateTDataSheetErr + e.GetType().ToString());
            }
        }
    }
}
